/**
 * 获取足迹列表接口
 */

//引入Q模块
let Q = require('q');

//引入公共函数
let util = require('../../util');

//引入fs模块
let fs = require('fs');

let redis;

let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	redis = _redis;
	//判断是否传进了登录code
	if(postData.wxCode) {
		//预定义存放公共数据库操作实例的变量
		let commonDB;
		//预定义存放用户ID的变量
		let userId = '';
		//调用函数假借登录获取用户ID
		getUserId(config.clientAppId, config.clientAppSecret, config.grantType, postData.wxCode, postData._3rdSession).then(function(_userId) {
			//取得用户ID
			userId = _userId;
			//连接到公共数据库
			return db.connectDB('common');
		}, function() {
			//获取用户ID失败
			deferred.reject('-0081');
		}).then(function(_commonDB) {
			//存放公共数据库实例
			commonDB = _commonDB;
			//查询得到用户的信息
			return commonDB.select('users', {
				userId: userId
			});
		}, function() {
			//连接公共数据库失败
			deferred.reject('-0044');
		}).then(function(userData) {
			//判断是否存在此用户
			if(userData.length == 0) {
				//直接返回无足迹
				deferred.resolve([]);
			}
			else {
				//得到该用户的数据
				userData = userData[0];
				//判断此用户是否不存在足迹
				if(!userData.userCurrentStore || userData.userCurrentStore.length == 0) {
					//返回无足迹
					deferred.resolve([]);
					return deferred.promise;
				}
				else {
					//预定义用于or查询信息的数组
					var currentStoreList = [];
					//遍历用户的足迹商铺ID
					for(var storeIndex in userData.userCurrentStore) {
						//将商铺ID存入待查询的列表
						currentStoreList.push({
							storeId: userData.userCurrentStore[storeIndex].storeId
						});
						//判断是否已经遍历完成
						if(storeIndex == userData.userCurrentStore.length - 1) {
							//查询出足迹中记载的商铺列表的商铺信息
							return commonDB.select('storeList', {
								$or: currentStoreList
							});
						}
					}
				}	
			}
		}, function() {
			//查询用户数据失败
			deferred.reject('-0080');
		}).then(function(currentStoreList) {
			if(currentStoreList.length == 0) {
				deferred.resolve([]);
			}
			else {
				var newCurrentStoreList = [];
				for(var storeIndex in currentStoreList) {
					newCurrentStoreList.push({
						//商户ID
						storeId: currentStoreList[storeIndex].storeId,
						//商户名称
						storeName: currentStoreList[storeIndex].storeName,
						//商户评星
						storeStar: currentStoreList[storeIndex].storeStar,
						//商户电话
						storePhone: currentStoreList[storeIndex].storePhone,
						//商户地址
						storeAdress: currentStoreList[storeIndex].storeAdress
					});
					if(storeIndex == currentStoreList.length - 1) {
						//查询足迹成功返回足迹数据
						deferred.resolve(newCurrentStoreList);
					}
				}
			}
		}, function() {
			//查询商铺信息列表失败
			deferred.reject('-0082');
		});
	}
	else {
		//查询足迹时未发现登录code参数
		deferred.reject('-0080');
	}
	return deferred.promise;
}

//获取userId函数
let getUserId = function(appId, appSecret, grantType, wxCode, _3rdSession) {
	let deferred = Q.defer();
	let getWxUserId = function() {
		let deferred = Q.defer();
		//发送GET请求到微信服务器请求sessionKey和用户数据
		util.get('https://api.weixin.qq.com/sns/jscode2session', {
			//小程序appid
			appid: appId,
			//小程序appSecret密钥
			secret: appSecret,
			//登录code
			js_code: wxCode,
			//登录类型
			grant_type: grantType
		}).then(function(data) {
			//判断是否存在session_key这个值
			console.log(data);
			if(data.openid) {
				//返回数据
				deferred.resolve(data.openid);
			}
			else {
				//参数不够返回失败
				deferred.reject();
			}
		}, function() {
			//请求失败
			deferred.reject();
		});
		return deferred.promise;
	}
	if(_3rdSession) {
		console.log('通过redis获取用户ID');
		redis.get(_3rdSession).then(function(data) {
			if(data) {
				data = JSON.parse(data);
				if(data.openId) {
					deferred.resolve(data.openId);
				}
				else {
					return getWxUserId();
				}
			}
			else {
				return getWxUserId();
			}
		}, function(err) {
			console.log(err);
			return getWxUserId();
		}).then(function(userId) {
			deferred.resolve(userId);
		}, function() {
			deferred.reject();
		});
	}
	else {
		getWxUserId().then(function(userId) {
			deferred.resolve(userId);
		}, function() {
			deferred.reject();
		});
	}
	return deferred.promise;
}

module.exports = {
	index: index
}